﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using Bussiness;

namespace GUI
{
    public partial class frmHoaDonBanSach : Form
    {
        private List<KhachHangDTO> _khachHangList;
        private DataTable _sachTable;

        public frmHoaDonBanSach()
        {
            InitializeComponent();
        }

        private void frmHoaDonBanSach_Load(object sender, EventArgs e)
        {
            ThamSoService tsSer = new ThamSoService();

            //tao ra ma hoa don moi
            HoaDonBanSachService hdSer = new HoaDonBanSachService();
            tbxMaHoaDon.Text = hdSer.CreateMaHoaDonBanSach();            
            //nap tham so
            //so luong ban toi thieu, no toi thieu

            //load khách hàng
            //gán vào biến toàn cục
            KhachHangService khService = new KhachHangService();
            _khachHangList = khService.GetKhachHangList();

            //gán vào danh sách khách hàng trên combobox
            cbxMaKhachHang.DataSource = _khachHangList;
            cbxMaKhachHang.DisplayMember = KhachHangColumn.MaKhachHang;

            //load danh sách sách, gán vào biến toàn cục
            SachService sachService = new SachService();
            _sachTable = sachService.GetSachListDetail();

            //gán vào combobox trên datagridview
            //cài đặt sự kiện cho nó
            maSachColumn.DataSource = _sachTable;
            maSachColumn.DisplayMember = SachComlumn.MaSach;
            maSachColumn.ValueMember = SachComlumn.IDSach;

            tbxTongCong.Text = "0";
        }

       
        private void btnThoat_Click(object sender, EventArgs e) {
            Close();
        }

        private void btnLapHoaDon_Click(object sender, EventArgs e) {
            //if chua co sach nao thi return
            if (dgvDanhSach.RowCount == 1) {
                MessageBox.Show("chua nhap sach");
                return;
            }


            ThamSoService tsSer = new ThamSoService();           

            //chi tiet hoa don
            List<ChiTietHoaDonBanSachDTO> chiTietList = new List<ChiTietHoaDonBanSachDTO>();

            //lấy thông tin khách hàng                        
            KhachHangDTO khDTO = new KhachHangDTO();
            khDTO = (KhachHangDTO)cbxMaKhachHang.Items[cbxMaKhachHang.SelectedIndex];

            ///tong gia tien
            int totalPrice = 0;

            int temp = 0;

            //kiem tra dieu kien tren datagridview
            //--xet xem co 2 sach nao trung nhau hay ko
            for(int i = 0; i <  dgvDanhSach.RowCount - 1; i++) {
                for (int j = i + 1; j < dgvDanhSach.RowCount - 1; j++) {
                    if (dgvDanhSach.Rows[i].Cells["idSachColumn"].Value == dgvDanhSach.Rows[j].Cells["idSachColumn"].Value) {
                        MessageBox.Show("2 sach trung nhau");
                        dgvDanhSach.CurrentCell = dgvDanhSach.Rows[i].Cells["idSachColumn"];
                        return;
                    }
                }
            }

            //tim xem co sach nao ko dap ung yeu cau hay k
            temp = tsSer.GetRules(ThamSoRows.SachTonSauKhiBan);
            for (int i = 0; i < dgvDanhSach.RowCount - 1; i++) {
                if (Convert.ToInt32(dgvDanhSach.Rows[i].Cells["soLuongTonColumn"].Value) - Convert.ToInt32(dgvDanhSach.Rows[i].Cells["soLuongBanColumn"].Value) < temp) {
                    MessageBox.Show("số lượng sách tồn sau khi bán ít nhất là: " + temp);
                    dgvDanhSach.CurrentCell = dgvDanhSach.Rows[i].Cells[1];
                    return;
                }
                else { //neu dung yeu cau thi ghi nhan chi tiet nay
                    ChiTietHoaDonBanSachDTO ctDTO = new ChiTietHoaDonBanSachDTO();
                    ctDTO.SoLuong = Convert.ToInt32(dgvDanhSach.Rows[i].Cells["soLuongBanColumn"].Value);
                    ctDTO.IDSach = Convert.ToInt32(dgvDanhSach.Rows[i].Cells["idSachColumn"].Value);
                    ctDTO.DonGiaBan = Convert.ToInt32(dgvDanhSach.Rows[i].Cells["donGiaBanColumn"].Value);

                    chiTietList.Add(ctDTO);
                    totalPrice += Convert.ToInt32(dgvDanhSach.Rows[i].Cells["thanhTienColumn"].Value);       
                }
            }

            //cập nhật dto
            HoaDonBanSachDTO hoaDonDTO = new HoaDonBanSachDTO();
            hoaDonDTO.IDKhachHang = khDTO.IDKhachHang;
            hoaDonDTO.MaHoaDonBanSach = tbxMaHoaDon.Text;
            hoaDonDTO.NgayLap = dtpNgayLapHD.Value;
            hoaDonDTO.TongGia = totalPrice;
                        
            //chuyen xuong service
            HoaDonBanSachService hoaDonSer = new HoaDonBanSachService();
            string mess = "Them hoa don thanh cong";
            hoaDonSer.InsertNewHoaDonBanSach(hoaDonDTO, chiTietList, khDTO, ref mess);
            //show messagebox
            MessageBox.Show(mess);            
        }

        private void dgvDanhSach_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) {
            //gan su kien cho combobox tren gridview
            if (dgvDanhSach.CurrentCell.ColumnIndex == 1) {
                ComboBox comboBox = e.Control as ComboBox;
                comboBox.SelectedIndexChanged += new System.EventHandler(this.comboBox_SelectIndexChanged);
                comboBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                comboBox.AutoCompleteSource = AutoCompleteSource.ListItems;
                comboBox.DropDownStyle = ComboBoxStyle.DropDown;
            }
        }

        #region su kien cho combobox tren gridview
        private void comboBox_SelectIndexChanged(object sender, EventArgs e) {
            int index = ((ComboBox)sender).SelectedIndex;
            if (index != -1) {
               
                // DataTable table = (DataTable)maSachComlumn.DataSource;
                dgvDanhSach.CurrentRow.Cells["tenSachColumn"].Value = _sachTable.Rows[index][SachComlumn.TenSach];
                dgvDanhSach.CurrentRow.Cells["soLuongTonColumn"].Value = _sachTable.Rows[index][SachComlumn.SoLuongTon];
                dgvDanhSach.CurrentRow.Cells["donGiaColumn"].Value = _sachTable.Rows[index][SachComlumn.DonGiaSach];
                dgvDanhSach.CurrentRow.Cells["tacGiaColumn"].Value = _sachTable.Rows[index][TacGiaColumn.TenTacGia];
                dgvDanhSach.CurrentRow.Cells["theLoaiColumn"].Value = _sachTable.Rows[index][TheLoaiColumn.TenTheLoai];
                dgvDanhSach.CurrentRow.Cells["idSachColumn"].Value = _sachTable.Rows[index][SachComlumn.IDSach];
                dgvDanhSach.CurrentRow.Cells["soLuongBanColumn"].Value = 1;
                dgvDanhSach.CurrentRow.Cells["donGiaBanColumn"].Value = _sachTable.Rows[index][SachComlumn.DonGiaSach];
                dgvDanhSach.CurrentRow.Cells["thanhTienColumn"].Value = _sachTable.Rows[index][SachComlumn.DonGiaSach];

                int total = 0;
                for (int i = 0; i < dgvDanhSach.RowCount; i++)
                    total += Convert.ToInt32(dgvDanhSach.Rows[i].Cells["thanhTienColumn"].Value);

                tbxTongCong.Text = total.ToString();
            }
        }
        #endregion

        private void cbxMaKhachHang_SelectedIndexChanged(object sender, EventArgs e) {
            if (cbxMaKhachHang.SelectedIndex != -1) {
                KhachHangDTO khDTO = new KhachHangDTO();
                khDTO = (KhachHangDTO)cbxMaKhachHang.Items[cbxMaKhachHang.SelectedIndex];

                tbxNoKhachHang.Text = khDTO.TienNo.ToString();
                tbxTenKhachHang.Text = khDTO.HoTen;
                txtDiaChi.Text = khDTO.DiaChi;

                dgvDanhSach.ReadOnly = false;
            }
            else
                dgvDanhSach.ReadOnly = true;
        }

        private void dgvDanhSach_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {
            //xem xet lai stt [cach cu chuoi]
            for (int i = 0; i < dgvDanhSach.RowCount - 1; i++)
                dgvDanhSach.Rows[i].Cells["sttColumn"].Value = i + 1;
        }

        private void dgvDanhSach_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
            #region #######
            ////if cell nay la cbx
            //if (e.ColumnIndex == 1) {
            //    //kiem tra co bi trung ko
            //    int currentIDSach = Convert.ToInt32(dgvDanhSach.CurrentCell.Value);
            //   // int flag = 0;
            //    if (dgvDanhSach.RowCount > 1) {
            //        for (int i = 0; i < dgvDanhSach.RowCount - 1; i++) {
            //            if (currentIDSach == Convert.ToInt32(dgvDanhSach.Rows[i].Cells[1].Value)) {
            //                //dgvDanhSach.CurrentRow.Cells["tenSachColumn"].Value = "";
            //                //dgvDanhSach.CurrentRow.Cells["soLuongTonColumn"].Value = "";
            //                //dgvDanhSach.CurrentRow.Cells["donGiaColumn"].Value = "";
            //                //dgvDanhSach.CurrentRow.Cells["tacGiaColumn"].Value = "";
            //                //dgvDanhSach.CurrentRow.Cells["theLoaiColumn"].Value = "";
            //                //dgvDanhSach.CurrentRow.Cells["idSachColumn"].Value = "";
            //                //dgvDanhSach.CurrentRow.Cells["soLuongBanColumn"].Value = 0;

            //                ////dgvDanhSach.CurrentCell = dgvDanhSach.CurrentRow.Cells[1];
            //                //e.Cancel = true;
            //                //return;

            //                flag = 1;
            //            }
            //        }
            //    }

            //    //if (flag == 1)
            //       // e.Cancel = true;
            //}
            #endregion

            //cap nhat thanh tien va tong tien
            if ((e.ColumnIndex == 5 || e.ColumnIndex == 8) && dgvDanhSach.CurrentRow.Index != dgvDanhSach.RowCount - 1) { //neu la cot so luong hoac cot don gia duoc edit
                //neu so luong ban la 0 hoac rong thi cap nhat lai la 1
                if (e.ColumnIndex == 5) {
                    if (Convert.ToInt32(dgvDanhSach.CurrentRow.Cells[e.ColumnIndex].Value) == 0) {
                        MessageBox.Show("chua nhap so luong sach ban");
                        dgvDanhSach.CurrentRow.Cells["soLuongBanColumn"].Value = 1;
                        dgvDanhSach.CurrentCell = dgvDanhSach.CurrentRow.Cells[5];
                        return;
                    }
                }

                //neu don gia ban la rong thi cap nhat lai la gia cua don gia
                if (e.ColumnIndex == 8) {
                    if (Convert.ToInt32(dgvDanhSach.CurrentRow.Cells[e.ColumnIndex].Value) == 0) {
                        MessageBox.Show("chua nhap don sach ban");
                        dgvDanhSach.CurrentRow.Cells["donGiaBanColumn"].Value = dgvDanhSach.CurrentRow.Cells["donGiaColumn"].Value;
                        dgvDanhSach.CurrentCell = dgvDanhSach.CurrentRow.Cells[8];
                        return;
                    }
                }
                //cap nhat lai tong gia
                int total = Convert.ToInt32(dgvDanhSach.CurrentRow.Cells["donGiaBanColumn"].Value) * Convert.ToInt32(dgvDanhSach.CurrentRow.Cells["soLuongBanColumn"].Value);
                dgvDanhSach.CurrentRow.Cells["thanhTienColumn"].Value = total;

                total = 0;
                for (int i = 0; i < dgvDanhSach.RowCount; i++)
                    total += Convert.ToInt32(dgvDanhSach.Rows[i].Cells["thanhTienColumn"].Value);

                tbxTongCong.Text = total.ToString();
            }
        }

        private void dgvDanhSach_CurrentCellDirtyStateChanged(object sender, EventArgs e) {
            dgvDanhSach.CommitEdit(DataGridViewDataErrorContexts.Commit);
        }        

        private void btnXoa_Click(object sender, EventArgs e) {
            if (dgvDanhSach.CurrentRow.Index != dgvDanhSach.RowCount - 1) {
                dgvDanhSach.Rows.RemoveAt(dgvDanhSach.CurrentRow.Index);
                for (int i = 0; i < dgvDanhSach.RowCount - 1; i++)
                    dgvDanhSach.Rows[i].Cells["sttColumn"].Value = i + 1;
            }
        }

        private void dgvDanhSach_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) {
            for (int i = 0; i < dgvDanhSach.RowCount - 1; i++)
                dgvDanhSach.Rows[i].Cells["sttColumn"].Value = i + 1;
        }

        private void gbxThongTinChung_Enter(object sender, EventArgs e) {

        }

        private void btnLamMoi_Click(object sender, EventArgs e) {
            //xoa du lieu tren dgv
            dgvDanhSach.Rows.Clear();
            tbxTongCong.Text = "0";
        }

    }
}
